package com.ssyx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssyx.exception.SsyxException;
import com.ssyx.helper.PermissionHelper;
import com.ssyx.mapper.PermissionMapper;
import com.ssyx.mapper.RolePermissionMapper;
import com.ssyx.model.acl.Permission;
import com.ssyx.model.acl.RolePermission;
import com.ssyx.result.ResultCodeEnum;
import com.ssyx.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: ssyx-parent
 * @className: PermissionServiceImpl
 * @description: 权限服务
 * @data: 2024/3/7 15:07
 * @author: ihu
 * @version: 1.0
 **/

@Slf4j
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
		implements PermissionService {
	@Resource
	private RolePermissionMapper rolePermissionMapper;
	
	// 获取所有菜单
	@Override
	public List<Permission> queryAllMenu() {
		// 获取全部权限数据
		List<Permission> allPermissionList = list(new QueryWrapper<Permission>().orderByAsc("CAST(id AS" +
				" " +
				"SIGNED)"));
		//把权限数据构建成树形结构数据
		return PermissionHelper.bulid(allPermissionList, null);
	}
	
	//递归删除菜单
	@Transactional
	@Override
	public void removeChildById(Long id) {
		List<Long> idList = new ArrayList<>();
		selectChildListById(id, idList);
		idList.add(id);
		removeByIds(idList);
	}
	
	@Override
	public List<Permission> toAssign(Long roleId) {
		List<RolePermission> rolePermissions = rolePermissionMapper.selectList(new QueryWrapper<RolePermission>().eq(
				"role_id", roleId));
		List<Permission> allPermissionList = baseMapper.selectList(new QueryWrapper<Permission>().orderByAsc("CAST(id AS" +
				" " +
				"SIGNED)"));
		return PermissionHelper.bulid(allPermissionList, rolePermissions);
	}
	
	@Transactional
	@Override
	public void doAssign(Long roleId, Long[] permissionId) {
		if (permissionId == null) {
			log.error(String.valueOf(ResultCodeEnum.DATA_ERROR));
			throw new SsyxException(ResultCodeEnum.DATA_ERROR);
		}
		rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", roleId));
		for (Long perId : permissionId) {
			RolePermission rolePer = new RolePermission();
			rolePer.setRoleId(roleId);
			rolePer.setPermissionId(perId);
			rolePer.setCreateTime(new Date());
			rolePer.setUpdateTime(new Date());
			rolePermissionMapper.insert(rolePer);
		}
	}
	
	/**
	 * 递归获取子节点
	 */
	private void selectChildListById(Long id, List<Long> idList) {
		List<Permission> childList = list(new QueryWrapper<Permission>().eq("pid", id).select("id"));
		childList.forEach(item -> {
			idList.add(item.getId());
			selectChildListById(item.getId(), idList);
		});
	}
	
}
